package com.example.index.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.yc.vo.Result;
import org.apache.commons.io.FilenameUtils;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
public class UploadController {


    //阿里域名
    public static final String ALI_DOMAIN = "https://3tuo1.oss-cn-guangzhou.aliyuncs.com/";

    @RequestMapping("/uploadImg")
    public  Result uploadImage(MultipartFile file) throws IOException {
        //生成文件名
        String originalFilename = file.getOriginalFilename();//原来的图片名
        String ext = "." + FilenameUtils.getExtension(originalFilename);
        String uuid = UUID.randomUUID().toString().replace("-","");
        String fileName = uuid + ext;
        //地域节点
        String endpoint = "http://oss-cn-guangzhou.aliyuncs.com";
        String accessKeyId = "LTAI5tEYim3kFmMrZFPpARdd";
        String accessKeySeret = "acwc1yITbIb1vraktnm4JP5kE1xcEd";
        //OSS客户端对象
        OSS ossClient = new OSSClientBuilder().build(endpoint,accessKeyId,accessKeySeret);
        ossClient.putObject("3tuo1", fileName, file.getInputStream());
        ossClient.shutdown();
        return Result.success("success",ALI_DOMAIN + fileName);
    }




    @RequestMapping("/upload")
    public Result upload(MultipartFile file) throws IOException {
        //这里需要注意的是ApplicationHome是属于SpringBoot的类
        ApplicationHome applicationHome=new ApplicationHome(this.getClass());
        System.out.println(applicationHome.getDir().getParentFile().getParentFile().getAbsolutePath());
        String path=applicationHome.getDir().getParentFile().getParentFile().getAbsolutePath()+"\\src\\main\\resources\\static\\images\\houseImg";
        String filename = file.getOriginalFilename();
        String suffix=filename.substring(filename.lastIndexOf("."));
        filename= UUID.randomUUID().toString().replaceAll("-","")+suffix;
        File files=new File(path,filename);
        File parentFile = files.getParentFile();
        if (!parentFile.exists()){
            parentFile.mkdir();
        }
        file.transferTo(files);
        return Result.success("success",filename);
    }
}
